﻿using System;
using System.Drawing;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Globalization;
using System.Text;
using System.Collections;

namespace VSM
{
    public partial class PartOrder : System.Web.UI.Page
    {
        private static DataTable dtDealer;
        private static DataTable dtContents;
        private static GeneralFunctions GF = null;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

                dtContents = new DataTable();
                createEmptyTable();
                grvPO.DataSource = dtContents;
                grvPO.DataBind();
                // Add code check security here


                if (Request.QueryString["id"] != null && Request.QueryString["id"].Length > 0)
                {
                    //txtDealerCode.ReadOnly = true;
                    //txtDealerCode.BackColor = ColorTranslator.FromHtml("#E6E6E6");
                    DealerCode.Value = Request.QueryString["id"];
                    //btnUpdate.Text = "Update Dealer";
                    if (string.Compare("VSM", (string)Session[Utils.AppConstants.ID_Dealer]) == 0)
                    {
                        LoadData(Utils.AppConstants.VSM, Request.QueryString["id"].ToString());
                    }
                }
                else if (string.Compare("VSM", (string)Session[Utils.AppConstants.ID_Dealer]) == 0) // Add new dealer
                {
                    //btnUpdate.Text = "Add Dealer";
                    DealerCode.Value = "";
                }
            }
        }

        private void createEmptyTable()
        {
            dtContents.Columns.Add("No");
            dtContents.Columns.Add("detID");
            dtContents.Columns.Add("ItemCode");
            dtContents.Columns.Add("ItemName");
            dtContents.Columns.Add("FrgnName");
            dtContents.Columns.Add("Quantity");
            dtContents.Columns.Add("Price");
            dtContents.Columns.Add("VAT");
            dtContents.Columns.Add("DiscPrcnt");
            dtContents.Columns.Add("Stock");

        }
        /// <summary>
        /// 
        /// </summary>
        private void LoadData(string dbType, string CardCode)
        {
            Transaction trx = new Transaction();
            DataSet dsDealer = trx.GetMarketingDocument_ReturnDS( ((ulong)DocType.BUSINESS_PARTNER).ToString(), CardCode, dbType);
            dtDealer = dsDealer.Tables[0];
            BindData(dtDealer);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="tblData"></param>
        private void BindData(DataTable tblData)
        {
            if (tblData.Rows.Count > 0)
            {
                DataRow dr = tblData.Rows[0];
                //txtDealerCode.Text = dr["CardCode"].ToString();
                //txtDealerName.Text = dr["CardName"].ToString();
                //txtAddress.Text = dr["Address"].ToString();
                //txtTaxCode.Text = dr["LicTradNum"].ToString();
                //txtTel1.Text = dr["Phone1"].ToString();
                //txtTel2.Text = dr["Phone2"].ToString();
                //txtMobilePhone.Text = dr["Cellular"].ToString();
                //txtEmail.Text = dr["E_mail"].ToString();
                //txtFax.Text = dr["Fax"].ToString();
            }
        }

        protected void btn_New_Click(object sender, EventArgs e)
        {

            txtRONo.Text = "RO-" + "003/0414";

            txtDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
      
        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            //if (txtDealerCode.Text == "")
            //{
            //    Session["errorMessage"] = "Missing Dealer Code";
            //    Session["requestXML"] = "";
            //    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('Missing Dealer Code','');", true);
            //}
            /*
            String requestXML = _collectData();
            Transaction ts = new Transaction();

            DataSet ds = ts.CreateMarketingDocument(requestXML, ((ulong)DocType.BUSINESS_PARTNER).ToString(), txtDealerCode.Text, !string.IsNullOrEmpty(DealerCode.Value), Utils.AppConstants.VSM
            );

            if ((int)ds.Tables[0].Rows[0]["ErrCode"] != 0)
            {
                Session["errorMessage"] = ds.Tables[0].Rows[0]["ErrMsg"];
                Session["requestXML"] = requestXML;
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ds.Tables[0].Rows[0]["ErrMsg"].ToString()) + "','');", true);
            }
            else
            {
                Session["successMessage"] = "Operation complete sucessful!";
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + "Operation complete sucessful!" + "','');", true);
            }
            ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
       
             */
        }
        protected void txtPODate_TextChanged(object sender, EventArgs e)
        {
            try
            {
                //Check Valid Date
               // Utils.AppConstants.ConvertToDate(this.txtPODate.Text.Trim());
               // this.btnShowPopup.Enabled = true;
            }
            catch
            {
                //this.btnShowPopup.Enabled = false;
            }
            //UpdatePrice();
        }
        private String _collectData()
        {
            try
            {
                DataTable dt = new DataTable("OCRD");
                dt.Columns.Add("CardCode");
                dt.Columns.Add("CardName");
                dt.Columns.Add("Address");
                dt.Columns.Add("LicTradNum");
                dt.Columns.Add("Phone1");
                dt.Columns.Add("Phone2");
                dt.Columns.Add("CardType");
                dt.Columns.Add("GroupCode");
                dt.Columns.Add("Cellular");
                dt.Columns.Add("Fax");
                dt.Columns.Add("E_Mail");
                
                DataRow dr = dt.NewRow();

                //dr["CardCode"] = txtDealerCode.Text;
                //dr["CardName"] = txtDealerName.Text;
                //dr["Address"] = txtAddress.Text;
                //dr["LicTradNum"] = txtTaxCode.Text;
                //dr["Phone1"] = txtTel1.Text;
                //dr["Phone2"] = txtTel2.Text;
                //dr["CardType"] = "C";
                //dr["GroupCode"] = "104";
                //dr["Cellular"] = txtMobilePhone.Text;
                //dr["Fax"] = txtFax.Text;
                //dr["E_Mail"] = txtEmail.Text;

                //dr["U_UserID"] = User.Identity.Name;
                DocumentXML objInfo = new DocumentXML();
                DataSet ds = new DataSet("DS");

                dt.Rows.Add(dr);

                ds.Tables.Add(dt.Copy());
                return objInfo.ToXMLStringFromDS(((ulong)DocType.BUSINESS_PARTNER).ToString(), ds);
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ex.ToString()) + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                return "";
            }
        }
 

        /// <summary>
        /// 
        /// </summary>
        private void ResetPage()
        {
            /*this.txtVendorCode.Text = "";
            this.txtVendorName.Text = "";
            this.Session["ChosenItem"] = null;
            this.Session["ChosenVendorCode"] = null;
            this.Session["ChosenVendorName"] = null;
            Session["SODATA"] = null;
            LoadOrderWareHouse();
            LoadData();
            this.btnUpdate.Enabled = false;*/
        }

        protected void btn_New0_Click(object sender, EventArgs e)
        {

        }
      
        protected void TextBox_Change(object sender, EventArgs e)
        {
            // string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;

            TextBox tb = (TextBox)sender;
            string ItemCode = "'" + tb.Text + "'";
            GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
            Label lblNo = (Label)row.FindControl("lblNo");
            int rowNo = Int32.Parse( lblNo.Text) -1;
            int index = 0;
            foreach (DataRow dr in dtContents.Rows) {
                if (rowNo == index) {

                    MasterData mt = new MasterData();
                    DataSet dsItem = mt.GetItemsByItemCodeList("VSM", Utils.AppConstants.ID_Dealer, ItemCode);
                    
                    if (dsItem.Tables[0].Rows.Count == 1) {
                        dr["ItemCode"] = dsItem.Tables[0].Rows[0]["ItemCode"];
                        dr["ItemName"] = dsItem.Tables[0].Rows[0]["ItemName"];
                        dr["FrgnName"] = dsItem.Tables[0].Rows[0]["FrgnName"];
                        dr["Quantity"] = 1;
                        dr["Price"] = 10000;//dsItem.Tables[0].Rows[0]["Price"];
                        dr["VAT"] = 10;//dsItem.Tables[0].Rows[0]["VAT"];
                        dr["DiscPrcnt"] = 10;//dsItem.Tables[0].Rows[0]["Discount"];
                        dr["Stock"] = 0; //dsItem.Tables[0].Rows[0]["Stock"];
                        grvPO.DataSource = dtContents;
                        grvPO.DataBind();

                        this.lblError.Visible = false;
                        break;
                    }
                    else if (dsItem.Tables[0].Rows.Count > 1)
                    {
                        string msg = "Available parts: ";
                        foreach (DataRow drItem in dsItem.Tables[0].Rows)
                        {
                            msg += "";
                        }
                        this.lblError.Text = msg;
                        this.lblError.Visible = true;
                        break;
                    }
                    else { //=0
                        this.lblError.Text = "There is no part with code [" + tb.Text + "] available ";
                        this.lblError.Visible = true;
                    }
                    
                }
                index++;
            }

            
           

            //ListViewItem lvi = e.Item;

            //Label lblNo = (Label)lvi.FindControl("lblNo");
            //foreach (DataRow row in dtContents.Rows)
            //{
            //    if (row["No"].ToString().Equals(lblNo.Text)) // update currentrow into data table
            //    {
            //        Label lx = (Label)lvi.FindControl("ItemName");
            //        lx.Text = "Ha ha ha ha";

            //        //row["ItemCode"] = ((Label)lvi.FindControl("lblCode")).Text;
            //        //row["Dscription"] = ((Label)lvi.FindControl("lblDescription")).Text;
            //        //row["Quantity"] = ((TextBox)lvi.FindControl("txtQuantity")).Text;
            //        break;
            //    }
            //}
        }

        protected void btn_AddMultiItems_Click(object sender, EventArgs e)
        {
            dtContents.Rows.Add(dtContents.Rows.Count, "", "", "", "", "", "", "", "", "");
            this.grvPO.DataSource = dtContents;
            this.grvPO.DataBind();
        }

        //RUKOWEN ADDED
        protected void grvPO_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                GridViewRow myRow = e.Row;
                Label lblNo = myRow.FindControl("lblNo") as Label;
                lblNo.Text = (myRow.RowIndex + 1).ToString();
                //if (this.hdnStatus.Value == "C")
                //{
                //    TextBox txtQuantity = myRow.FindControl("txtOrderQuantity") as TextBox;
                //    txtQuantity.Enabled = false;
                //}
            }
        }

        protected void grvSearchResult_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            this.grvPO.PageIndex = e.NewPageIndex;
            DataTable tblPOR1 = (DataTable)Session["POR1Table"];
            BindData(tblPOR1);
        }

        private void CalcTotal(DataTable tb)
        {
            try
            {
                double documentTotal = 0;
                double gstTotal = 0;
                double subTotal = 0;
                foreach (DataRow row in tb.Rows)
                {
                    subTotal += double.Parse(row["LineTotal"].ToString());
                    if (row["VatPrcnt"] != null && row["VatPrcnt"].ToString().Length > 0)
                    {
                        gstTotal += (double.Parse(row["LineTotal"].ToString()) * double.Parse(row["VatPrcnt"].ToString())) / 100;
                    }
                    else
                    {
                        gstTotal += (double.Parse(row["LineTotal"].ToString()) * 8.25) / 100;
                    }
                }
                documentTotal += subTotal + gstTotal;
                //this.lblDocumentTotal.Text = string.Format("{0:C}", Math.Round(documentTotal, 2));
                //this.lblTaxAmount.Text = string.Format("{0:C}", Math.Round(gstTotal, 2));
                //this.lblSubTotal.Text = string.Format("{0:C}", Math.Round(subTotal, 2));
            }
            catch (Exception ex)
            {
                string alert = "alert('Error: " + ex.Message + " ');";
                ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", alert, true);
            }
        }

        protected void grvSearchResult_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            /*
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes.Add("onmouseover", "MouseEvents(this, event)");
                e.Row.Attributes.Add("onmouseout", "MouseEvents(this, event)");
                e.Row.Attributes["style"] = "cursor:pointer";
                int index = 0;
                TextBox ddl1 = e.Row.FindControl("txtOrderQuantity") as TextBox;
                ddl1.Attributes.Add("onfocus", "JavaScript:document.getElementById('" + ddl1.ClientID + "').select();");
                if (ViewState["rowindex"] != null && Session["POTable"] != null)
                {
                    index = Convert.ToInt32(ViewState["rowindex"].ToString());
                    int rowCount = ((DataTable)Session["POTable"]).Rows.Count;
                    if ((index + 1) <= this.grvPO.Rows.Count)
                    {
                        if (e.Row.RowIndex == index + 1)
                        {
                            ddl1.Focus();
                            //ScriptManager.GetCurrent(this).SetFocus(ddl1.ClientID);
                        }
                    }
                }
            }
             * */
        }

        protected void lnkDelete_Click(object sender, EventArgs e)
        {
            try
            {
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((LinkButton)sender).Parent).Parent;
                Label lblNo = (Label)row.FindControl("lblNo");
                int rowNo = Int32.Parse(lblNo.Text) - 1;
               
                foreach (DataRow dr in dtContents.Rows)
                {
                    if (rowNo == Int32.Parse(dr["No"].ToString())) {
                        dr.Delete();
                        break;
                    }
                }
                //reload number
                int index = 0;
                foreach (DataRow dr in dtContents.Rows)
                    dr["No"] = ++index;

                grvPO.DataSource = dtContents;
                grvPO.DataBind();
           

                /*
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((LinkButton)sender).Parent).Parent;
                Label lblItemCode = (Label)row.FindControl("lblItemCode");
                DataTable tb = (DataTable)Session["POR1Table"];
                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("ItemCode='" + lblItemCode.Text + "'");
                    if (rupdate.Length > 0)
                    {
                        Dictionary<string, string> dicItem = (Dictionary<string, string>)Session["ChosenItem"];
                        if (dicItem != null)
                        {
                            if (dicItem.ContainsKey(rupdate[0]["ItemCode"].ToString()))
                            {
                                dicItem.Remove(rupdate[0]["ItemCode"].ToString());
                            }
                        }
                        tb.Rows.Remove(rupdate[0]);
                    }
                    this.grvPO.EditIndex = -1;
                    BindData((DataTable)Session["POR1Table"]);
                    CalcTotal(((DataTable)Session["POR1Table"]));
                }
                 * */
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
              
        }

        public void updateRowTotalPrice(DataRow row, string currColName)
        {
            double quantity = 0, unitPrice = 0.0, discount = 0, priceAfterDiscount = 0.0, total = 0;
            quantity = GF.Object2Double(GF.ResetFormatNumeric(row["Quantity"].ToString()), "QtyDec");
            unitPrice = GF.Object2Double(GF.ResetFormatNumeric(row["PriceBefDi"].ToString()), "PriceDec");
            discount = GF.Object2Double(GF.ResetFormatNumeric(row["DiscPrcnt"].ToString()), "PercentDec");
            priceAfterDiscount = GF.Object2Double((Object)(unitPrice * (100 - discount) / 100), "PriceDec");

            total = GF.Object2Double((Object)(priceAfterDiscount * quantity), "SumDec");

            if (string.IsNullOrEmpty(currColName))
                row["Quantity"] = GF.FormatNumeric(quantity.ToString(), "QtyDec");
            if (string.IsNullOrEmpty(currColName) || currColName.Equals("PriceBefDi") || currColName.Equals("DiscPrcnt"))
                row["PriceBefDi"] = GF.FormatNumeric(unitPrice.ToString(), "PriceDec");
            if (string.IsNullOrEmpty(currColName) || currColName.Equals("PriceBefDi") || currColName.Equals("DiscPrcnt") || currColName.Equals("Quantity"))
                row["DiscPrcnt"] = GF.FormatNumeric(discount.ToString(), "PercentDec");

            row["Price"] = GF.FormatNumeric(priceAfterDiscount.ToString(), "PriceDec");
            row["LineTotal"] = GF.FormatNumeric(total.ToString(), "SumDec");

        }

        protected void txtOrderQuantity_OnTextChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                TextBox txtQuantity = (TextBox)row.FindControl("txtOrderQuantity");
                if (txtQuantity.Text.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input quantity');", true);
                    txtQuantity.Focus();
                    return;
                }
                Label lblItemCode = (Label)row.FindControl("lblItemCode");

                DataTable tb = (DataTable)Session["POR1Table"];
                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("ItemCode='" + lblItemCode.Text + "'");
                    if (rupdate.Length > 0)
                    {
                        rupdate[0]["Quantity"] = txtQuantity.Text;
                        updateRowTotalPrice(rupdate[0], "Quantity");
                    }
                }

                this.grvPO.EditIndex = -1;

                BindData(tb);
                CalcTotal(tb);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
           
        }

        protected void txtUnitPrice_OnTextChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                TextBox txtUnitPrice = (TextBox)row.FindControl("txtUnitPrice");
                if (txtUnitPrice.Text.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input quantity');", true);
                    txtUnitPrice.Focus();
                    return;
                }
                Label lblItemCode = (Label)row.FindControl("lblItemCode");

                DataTable tb = (DataTable)Session["POR1Table"];
                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("ItemCode='" + lblItemCode.Text + "'");
                    if (rupdate.Length > 0)
                    {
                        rupdate[0]["PriceBefDi"] = txtUnitPrice.Text;
                        updateRowTotalPrice(rupdate[0], "PriceBefDi");
                    }
                }

                this.grvPO.EditIndex = -1;

                BindData(tb);
                CalcTotal(tb);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        protected void EditItem(object sender, GridViewEditEventArgs e)
        {
            this.grvPO.EditIndex = e.NewEditIndex;
            BindData((DataTable)Session["POR1Table"]);
        }

        protected void CancelEdit(object sender, GridViewCancelEditEventArgs e)
        {
            e.Cancel = true;
            this.grvPO.EditIndex = -1;
            BindData((DataTable)Session["POR1Table"]);
        }

        private void GetPrice(DataRow r)
        {
            try
            {
                /*
                DataSet ds = GetDataItem(DateTime.Parse(this.txtPODate.Text.Trim()), r["ItemCode"].ToString(), this.txtVendorCode.Text, double.Parse(r["Quantity"].ToString()));
                if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    if (ds.Tables[0].Rows[0]["BuyUnitMsr"].ToString().ToUpper() == "CTN")
                    {
                        r["Price"] = (decimal.Parse(ds.Tables[0].Rows[0]["NumInBuy"].ToString()) * decimal.Parse(ds.Tables[0].Rows[0]["Price"].ToString())).ToString(Utils.AppConstants.NUMBER_FORMAT);
                    }
                    else
                    {
                        r["Price"] = decimal.Parse(ds.Tables[0].Rows[0]["Price"].ToString()).ToString(Utils.AppConstants.NUMBER_FORMAT);
                    }
                    r["LineTotal"] = (double.Parse(r["Price"].ToString()) * double.Parse(r["Quantity"].ToString())).ToString(Utils.AppConstants.NUMBER_FORMAT);
                }
                 * */
            }
            catch (Exception ex)
            {
                string alert = "alert('Error: " + ex.Message + " ');";
                ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", alert, true);
            }
        }

        protected void DeleteItem(object sender, GridViewDeleteEventArgs e)
        {
            try
            {
                e.Cancel = true;
                GridViewRow row = (GridViewRow)this.grvPO.Rows[e.RowIndex];
                Label lblItemCode = (Label)row.FindControl("lblItemCode");
                DataTable tb = (DataTable)Session["POR1Table"];
                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("ItemCode='" + lblItemCode.Text + "'");
                    if (rupdate.Length > 0)
                    {
                        Dictionary<string, string> dicItem = (Dictionary<string, string>)Session["ChosenItem"];
                        if (dicItem != null)
                        {
                            if (dicItem.ContainsKey(rupdate[0]["ItemCode"].ToString()))
                            {
                                dicItem.Remove(rupdate[0]["ItemCode"].ToString());
                            }
                        }
                        tb.Rows.Remove(rupdate[0]);
                    }
                    this.grvPO.EditIndex = -1;
                    BindData((DataTable)Session["POR1Table"]);
                    CalcTotal(((DataTable)Session["POR1Table"]));
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        protected void UpdateItem(object sender, GridViewUpdateEventArgs e)
        {
            try
            {
                ViewState["rowindex"] = e.RowIndex;
                GridViewRow row = (GridViewRow)this.grvPO.Rows[e.RowIndex];
                TextBox txtQuantity = (TextBox)row.FindControl("txtOrderQuantity");
                if (txtQuantity.Text.Trim().Length == 0 || int.Parse(txtQuantity.Text.Trim()) == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('In Quantity column, enter whole number greater than 0');", true);
                    txtQuantity.Focus();
                    return;
                }
                Label lblItemCode = (Label)row.FindControl("lblItemCode");

                DataTable tb = (DataTable)Session["POR1Table"];
                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("ItemCode='" + lblItemCode.Text + "'");
                    if (rupdate.Length > 0)
                    {
                        rupdate[0]["Quantity"] = txtQuantity.Text;
                        GetPrice(rupdate[0]);
                    }

                    this.grvPO.EditIndex = -1;

                    BindData(tb);
                    CalcTotal(tb);
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        protected void txtDiscPrcnt_OnTextChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                TextBox txtDiscPrcnt = (TextBox)row.FindControl("txtDiscPrcnt");
                if (txtDiscPrcnt.Text.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input quantity');", true);
                    txtDiscPrcnt.Focus();
                    return;
                }
                Label lblItemCode = (Label)row.FindControl("lblItemCode");

                DataTable tb = (DataTable)Session["POR1Table"];
                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("ItemCode='" + lblItemCode.Text + "'");
                    if (rupdate.Length > 0)
                    {
                        rupdate[0]["DiscPrcnt"] = txtDiscPrcnt.Text;
                        updateRowTotalPrice(rupdate[0], "DiscPrcnt");
                    }
                }

                this.grvPO.EditIndex = -1;

                BindData(tb);
                CalcTotal(tb);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        
    }
}